from django.shortcuts import render, redirect, reverse
from django.views import View

from app01.models import *

# Create your views here.

def book_list(request):
    books = Book.objects.all()
    return render(request, "bookmanage/book/book_list.html", {"book_list": books})


def book_delete(request, id):
    get_book_id = Book.objects.filter(pk=id)
    if get_book_id.first():
        get_book_id.delete()
    return redirect(reverse("book_list"))


class Bookchange(View):
    def get(self, request, id):
        get_bid = Book.objects.filter(pk=id)
        if get_bid:
            auther_list = Auther.objects.all()
            publish_list = Publish.objects.all()
            return render(request, "bookmanage/book/book_change.html",
                          {"book_list": get_bid.first(), "auther_list": auther_list,
                           "publish_list": publish_list})
        return redirect(reverse("book_list"))

    def post(self, request, id):
        get_bid = Book.objects.filter(pk=id)
        if get_bid:
            name = request.POST.get("name")
            price = request.POST.get("price")
            create_time = request.POST.get("create_time")
            auther = request.POST.getlist("auther")
            publish = request.POST.get("publish")
            # 更新数据
            get_bid.update(name=name, price=price, create_time=create_time, publish_id=publish)
            get_bid.first().auther.set(auther)
        return redirect(reverse("book_list"))


class Bookadd(View):
    def get(self, request):
        auther_list = Auther.objects.all()
        publish_list = Publish.objects.all()

        return render(request, "bookmanage/book/book_add.html",
                      {"auther_list": auther_list,
                       "publish_list": publish_list})

    def post(self, request):
        name = request.POST.get("name")
        price = request.POST.get("price")
        create_time = request.POST.get("create_time")
        auther = request.POST.getlist("auther")
        publish = request.POST.get("publish")

        book = Book.objects.create(name=name, price=price, create_time=create_time, publish_id=publish)
        book.auther.add(*auther)

        return redirect(reverse("book_list"))
